<?php
declare(strict_types=1);

namespace App\HttpController\Admin;

use App\Exception\Api\BadRequestException;
use App\Service\Auth\AuthService;
use App\Validate\Auth\AuthUserValidate;

class Auth extends AdminBase
{
    /** @var AuthService|null */
    protected $authService;

    protected function onRequest(?string $action): ?bool
    {
        $this->authService = app(AuthService::class);
        return parent::onRequest($action);
    }

    public function code()
    {
        return $this->authService->getCode();
    }

    public function info()
    {
        // todo::
        return [];
    }

    public function login()
    {
        $post = $this->_request->post();

        $validate = new AuthUserValidate();
        $isOk     = $validate->check($post);
        if ($isOk !== true) {
            return fail($validate->getError());
        }

        try {
            $result = $this->authService->login($post);
        } catch (BadRequestException $exception) {
            return fail($exception->getMessage());
        }

        return success($result);
    }

    public function logout()
    {
        try {
            $this->authService->logout($this->_request, $this->user->username);
        } catch (BadRequestException $exception) {
            return fail($exception->getMessage());
        }
    }
}
